package cn.spream.jstudy.ssi.service.user.impl;

import cn.spream.jstudy.ssi.common.PaginatedArrayList;
import cn.spream.jstudy.ssi.common.PaginatedList;
import cn.spream.jstudy.ssi.common.Result;
import cn.spream.jstudy.ssi.dao.user.UserDao;
import cn.spream.jstudy.ssi.domain.user.UserQuery;
import cn.spream.jstudy.ssi.domain.user.User;
import cn.spream.jstudy.ssi.manager.user.UserManager;
import cn.spream.jstudy.ssi.service.user.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created by IntelliJ IDEA.
 * User: sjx
 * Date: 13-5-20
 * Time: 下午1:14
 * To change this template use File | Settings | File Templates.
 */
public class UserServiceImpl implements UserService {

    private static final Log log = LogFactory.getLog(UserServiceImpl.class);

    private UserDao userDao;
    private UserManager userManager;

    @Override
    public boolean add(User user) {
        return userDao.add(user);
    }

    @Override
    public boolean update(User user) {
        boolean updated = false;
        if(user != null &&  user.getId() > 0){
            updated = userManager.update(user);
        }
        return updated;
    }

    @Override
    public User getById(long id) {
        User user = null;
        if(id > 0){
            user = userDao.getById(id);
        }
        return user;
    }

    @Override
    public Result list(UserQuery userQuery, int pageIndex, int pageSize) {
        Result result = new Result(false);
        PaginatedList<User> profitsPaginated = new PaginatedArrayList<User>();
        try {
            profitsPaginated = new PaginatedArrayList<User>(pageIndex, pageSize);
            profitsPaginated.setTotalItem(userDao.count(userQuery));
            userQuery.setStartIndex(profitsPaginated.getStartIndex());
            userQuery.setPageSize(pageSize);
            profitsPaginated.addAll(userDao.list(userQuery));
            result.addDefaultModel("users", profitsPaginated);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error("分页获取用户信息时出错了，userQuery=" +
                    userQuery + ",pageIndex=" + pageIndex + ",pageSize=" + pageSize, e);
        }
        return result;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
}
